import tkinter as tk
from tkinter import ttk, messagebox
from typing import Dict, List, Callable
import json

class DiscussionDialog:
    """讨论配置对话框"""
    
    def __init__(self, parent, models: Dict, on_confirm: Callable):
        self.parent = parent
        self.models = models
        self.on_confirm = on_confirm
        
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("AI讨论配置")
        self.dialog.geometry("600x500")
        self.dialog.resizable(True, True)
        
        # 居中显示
        self.dialog.transient(parent)
        self.dialog.grab_set()
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI界面"""
        main_frame = ttk.Frame(self.dialog, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 讨论轮数设置
        ttk.Label(main_frame, text="讨论轮数:").grid(row=0, column=0, sticky=tk.W, pady=(0, 5))
        self.rounds_var = tk.IntVar(value=3)
        rounds_spin = ttk.Spinbox(main_frame, from_=1, to=10, textvariable=self.rounds_var, width=5)
        rounds_spin.grid(row=0, column=1, sticky=tk.W, pady=(0, 5))
        
        # 模型选择框架
        model_frame = ttk.LabelFrame(main_frame, text="参与讨论的模型", padding="5")
        model_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(10, 5))
        model_frame.columnconfigure(1, weight=1)
        
        # 创建滚动区域
        canvas = tk.Canvas(model_frame)
        scrollbar = ttk.Scrollbar(model_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = ttk.Frame(canvas)
        
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )
        
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        
        # 模型选择控件
        self.model_vars = {}
        row = 0
        for model_name in self.models.keys():
            # 模型名称
            ttk.Label(scrollable_frame, text=model_name).grid(row=row, column=0, sticky=tk.W, padx=(0, 10))
            
            # 数量选择
            count_var = tk.IntVar(value=0)
            count_spin = ttk.Spinbox(scrollable_frame, from_=0, to=5, textvariable=count_var, width=3)
            count_spin.grid(row=row, column=1, sticky=tk.W, padx=(0, 20))
            
            self.model_vars[model_name] = count_var
            row += 1
        
        canvas.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        model_frame.rowconfigure(0, weight=1)
        
        # 调度模型选择
        ttk.Label(main_frame, text="调度模型:").grid(row=2, column=0, sticky=tk.W, pady=(10, 5))
        self.coordinator_var = tk.StringVar()
        coordinator_combo = ttk.Combobox(main_frame, textvariable=self.coordinator_var, 
                                       values=list(self.models.keys()), state="readonly")
        coordinator_combo.grid(row=2, column=1, sticky=tk.W, pady=(10, 5))
        
        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=2, pady=(20, 0))
        
        ttk.Button(button_frame, text="确认", command=self.on_confirm_click).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(button_frame, text="取消", command=self.dialog.destroy).pack(side=tk.LEFT)
        
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(1, weight=1)
    
    def on_confirm_click(self):
        """确认按钮点击事件"""
        # 验证至少选择2个模型
        total_models = 0
        for var in self.model_vars.values():
            try:
                count = var.get()
                if count == "":  # 处理空字符串
                    count = 0
                total_models += int(count)
            except (ValueError, tk.TclError):
                # 如果获取值失败，跳过这个模型
                continue
                
        if total_models < 2:
            messagebox.showerror("错误", "请至少选择2个参与讨论的模型！")
            return
        
        # 验证调度模型已选择
        if not self.coordinator_var.get():
            messagebox.showerror("错误", "请选择调度模型！")
            return
        
        # 构建配置数据
        config = {
            'rounds': self.rounds_var.get(),
            'scheduler_model': self.coordinator_var.get(),  # 修改键名
            'participant_models': {},  # 修改键名
        }
        
        for model_name, var in self.model_vars.items():
            count = var.get()
            if count > 0:
                config['participant_models'][model_name] = count  # 修改键名
        
        self.on_confirm(config)
        self.dialog.destroy()
    
    def get_config(self):
        """获取配置"""
        return {
            'rounds': self.rounds_var.get(),
            'participants': {name: var.get() for name, var in self.model_vars.items()},
            'coordinator': self.coordinator_var.get()
        }